<?php

namespace Rjyst\RjCategoryModule\Services;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class TableChecker
{
    /**
     * 检查表是否存在
     */
    public static function tableExists(string $tableName): bool
    {
        try {
            return Schema::hasTable($tableName);
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 检查数据库连接
     */
    public static function checkDatabaseConnection(): bool
    {
        try {
            DB::connection()->getPdo();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取表字段
     */
    public static function getTableColumns(string $tableName): array
    {
        try {
            return Schema::getColumnListing($tableName);
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * 验证表结构
     */
    public static function verifyTableStructure(string $tableName, array $requiredColumns): bool
    {
        if (!self::tableExists($tableName)) {
            return false;
        }

        $existingColumns = self::getTableColumns($tableName);

        foreach ($requiredColumns as $column) {
            if (!in_array($column, $existingColumns)) {
                return false;
            }
        }

        return true;
    }
}
